package com.definesys.smecrailtransit.module.lineCharts.Fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecManager.SmecKpManager.SmecKpUtils;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentLineDayBinding;
import com.definesys.smecrailtransit.module.lineCharts.LineChartsActivity;
import com.definesys.smecrailtransit.module.lineCharts.LineChartsPresenter;
import com.definesys.smecrailtransit.module.lineCharts.activity.SmecErrorListActivity;
import com.definesys.smecrailtransit.module.lineCharts.beans.DayReport;
import com.definesys.smecrailtransit.module.lineCharts.beans.EleErrorMsg;
import com.definesys.smecrailtransit.module.lineCharts.beans.YesReport;
import com.definesys.smecrailtransit.module.lineCharts.viewModel.DayReportViewModel;
import com.definesys.smecrailtransit.utils.CommonUtils;
import com.definesys.smecrailtransit.widget.ChartsController;
import com.github.mikephil.charting.charts.PieChart;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static android.view.View.VISIBLE;
import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SELECTION_MODE_RANGE;

/**
 * Created by xupeizuo on 2018/3/5.
 */

public class DayChartsFragment extends SmecBaseFragment<LineChartsPresenter> {

    private FragmentLineDayBinding fragmentLineDayBinding;
    public static final String GET_DAY_REPORT_SUCCESS="GET_DAY_REPORT_SUCCESS";
    public static final String GET_DAY_REPORT_FAILURE="GET_DAY_REPORT_FAILURE";
    private static final DateFormat FORMATTER = SimpleDateFormat.getDateInstance();
    private Calendar calendar = Calendar.getInstance();
    private static final SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
    private String requestDate="";
    private ProgressDialog progressDialog;
    private DayReportViewModel dayReportViewModel;

    private ArrayList<EleErrorMsg> errorEleList=new ArrayList<>();
    private ArrayList<YesReport> faultEleList=new ArrayList<>();

    @Override
    protected LineChartsPresenter getPersenter() {
        return new LineChartsPresenter(getContext());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentLineDayBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_line_day,container,false);
        initView();
        fragmentLineDayBinding.setDayView(dayReportViewModel);
        return fragmentLineDayBinding.getRoot();
    }

    private void initView(){
        dayReportViewModel=new DayReportViewModel();
        setDate();
        calendarlistener();

        fragmentLineDayBinding.smecEleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startErrorList(0);
            }
        });

        fragmentLineDayBinding.smecFauMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startErrorList(1);
            }
        });
    }

    private void startErrorList(int type){
        Intent intent=new Intent(getActivity(), SmecErrorListActivity.class);
        intent.putExtra("errorType",type);
        intent.putExtra("errEle",errorEleList);
        intent.putExtra("fauEle",faultEleList);
        getContext().startActivity(intent);
    }

    /**
     * 如果当前在7点之前则请求昨天的数据
     */
    private void setDate(){
        int now=calendar.get(Calendar.HOUR_OF_DAY);
        if(now<7){
            calendar.add(Calendar.DATE, -1);
            fragmentLineDayBinding.calendarText.setText(FORMATTER.format(calendar.getTime()));
            requestDate=sim.format(calendar.getTime());
        }else {
            fragmentLineDayBinding.calendarText.setText(FORMATTER.format(new Date()));
            requestDate=sim.format(new Date());
        }

       mPresenter.getDayReport(requestDate);
    }


    /**
     * 日期选择器
     */
    public void calendarlistener(){

        fragmentLineDayBinding.chooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fragmentLineDayBinding.calendar.getVisibility() == VISIBLE){
                    fragmentLineDayBinding.calendar.setVisibility(View.GONE);
                    return;
                }
                fragmentLineDayBinding.calendar.setVisibility(View.VISIBLE);
            }
        });
        fragmentLineDayBinding.calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                if(date !=null){
                    fragmentLineDayBinding.calendarText.setText(FORMATTER.format(date.getDate()));
                    if(!sim.format(date.getDate()).equals(requestDate)){
                        requestDate=sim.format(date.getDate());
                        fragmentLineDayBinding.calendar.setVisibility(View.GONE);
                        getDayReport();
                    }
                }
            }
        });
        fragmentLineDayBinding.calendarView.state().edit()
                .setFirstDayOfWeek(Calendar.MONDAY)
                .setMaximumDate(CalendarDay.from(Calendar.getInstance().get(Calendar.YEAR)
                        , Calendar.getInstance().get(Calendar.MONTH)
                        , Calendar.getInstance().get(Calendar.DATE)))
                .setCalendarDisplayMode(CalendarMode.MONTHS)
                .commit();
        fragmentLineDayBinding.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fragmentLineDayBinding.calendar.getVisibility() == VISIBLE){
                    fragmentLineDayBinding.calendar.setVisibility(View.GONE);
                }
            }
        });
    }

    public void getDayReport(){
        if(progressDialog == null){
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在获取日报表信息请稍后...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        fragmentLineDayBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                progressDialog.show();
                mPresenter.getDayReport(requestDate);
            }
        },400);
    }

    /**
     * 处理数据
     */
    private void dealWithData(DayReport dayReport){
        dealChart(fragmentLineDayBinding.pieChart,dayReport.getRunEleCount(),dayReport.getErrorEleCount(),new String[]{"#60b4ae","#e5857c"});
        dealChart(fragmentLineDayBinding.pieChartY,dayReport.getCallFaultCount(),dayReport.getAutoFaultCount(),new String[]{"#ba4689","#82d7e9"});
        dealChart(fragmentLineDayBinding.pieChartY2,dayReport.getFtFaultCount(),dayReport.getNotSelfFaultCount(),new String[]{"#ad58e7","#d97c5f"});
        dealWithEleList(dayReport);
    }

    private void dealWithEleList(DayReport dayReport){
        dayReportViewModel.setEleErrorMsg1(new EleErrorMsg());
        dayReportViewModel.setEleErrorMsg2(new EleErrorMsg());
        dayReportViewModel.setEleErrorMsg3(new EleErrorMsg());
        dayReportViewModel.setEleErrorMsg4(new EleErrorMsg());
        dayReportViewModel.setEleErrorMsg5(new EleErrorMsg());
        if(CommonUtils.notEmpty(dayReport.getErrorEleList())){
            for(int i=0;i<dayReport.getErrorEleList().size();i++){
                EleErrorMsg eleErrorMsg=dayReport.getErrorEleList().get(i);
                if(i == 0){
                    dayReportViewModel.setEleErrorMsg1(eleErrorMsg);
                    continue;
                }
                if(i == 1){
                    dayReportViewModel.setEleErrorMsg2(eleErrorMsg);
                    continue;
                }
                if(i == 2){
                    dayReportViewModel.setEleErrorMsg3(eleErrorMsg);
                    continue;
                }
                if(i == 3){
                    dayReportViewModel.setEleErrorMsg4(eleErrorMsg);
                    continue;
                }
                if(i == 4){
                    dayReportViewModel.setEleErrorMsg5(eleErrorMsg);
                    continue;
                }
                break;
            }
        }

        dayReportViewModel.setYesReport1(new YesReport());
        dayReportViewModel.setYesReport2(new YesReport());
        dayReportViewModel.setYesReport3(new YesReport());
        dayReportViewModel.setYesReport4(new YesReport());
        dayReportViewModel.setYesReport5(new YesReport());

        if(CommonUtils.notEmpty(dayReport.getFaultEleList())){
            for(int i=0;i<dayReport.getFaultEleList().size();i++){
                YesReport yesReport=dayReport.getFaultEleList().get(i);
                if(i == 0){
                    dayReportViewModel.setYesReport1(yesReport);
                    continue;
                }
                if(i == 1){
                    dayReportViewModel.setYesReport2(yesReport);
                    continue;
                }
                if(i == 2){
                    dayReportViewModel.setYesReport3(yesReport);
                    continue;
                }
                if(i == 3){
                    dayReportViewModel.setYesReport4(yesReport);
                    continue;
                }
                if(i == 4){
                    dayReportViewModel.setYesReport5(yesReport);
                    continue;
                }
                break;
            }
        }
    }

    private void dealChart(PieChart mPieChart,int num1,int num2,String[] coArr){
        ChartsController chartsController =new ChartsController(mPieChart,getContext(),coArr);
        chartsController.initPie();
        ArrayList<Integer> list2=new ArrayList<>();
        list2.add(num1);
        list2.add(num2);
        chartsController.setPieData(list2);
        chartsController.startLoaf();
    }

    public static DayChartsFragment newInstance() {
        Bundle args = new Bundle();
        DayChartsFragment fragment = new DayChartsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_DAY_REPORT_SUCCESS)
            }
    )
    public void getDayReportSuccess(DayReport dayReport){
        fragmentLineDayBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
               if(progressDialog!=null && progressDialog.isShowing()){
                   progressDialog.dismiss();
               }
            }
        },700);
        dayReportViewModel.setDayReport(dayReport);
        dealWithData(dayReport);
        fragmentLineDayBinding.invalidateAll();
        errorEleList=dayReport.getErrorEleList();
        faultEleList=dayReport.getFaultEleList();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_DAY_REPORT_FAILURE)
            }
    )
    public void getDayReportSuccess(Object o){
        fragmentLineDayBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(progressDialog!=null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }
        },700);
    }
}
